<?php

namespace Tuobaye\FilamentAdmin\Resources;

use Filament\Forms;
use Filament\Forms\Form;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Tuobaye\FilamentAdmin\Concerns\WithPermissions;
use Tuobaye\FilamentAdmin\Contracts\HasPermissions;
use Tuobaye\FilamentAdmin\Forms\PermissionCheckList;
use Tuobaye\FilamentAdmin\Models\Role;
use Tuobaye\FilamentAdmin\Resources\RoleResource\Pages;

class RoleResource extends Resource implements HasPermissions
{
    use WithPermissions;

    protected static ?string $model = Role::class;
    protected static ?string $label = '用户组';

    protected static ?string $navigationIcon = 'heroicon-o-user-group';

    protected static ?string $slug = 'admin/roles';

    public static function getPermissions(): array
    {
        return [
            'permission' => '设置权限'
        ];
    }


    public static function getNavigationGroup(): ?string
    {
        return config('filament-admin.resource.group');
    }

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\TextInput::make('name')->label('名称'),
            ])->columns(1);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('id')->label('ID')->sortable(),
                Tables\Columns\TextColumn::make('name')->label('名称')->searchable(),
                Tables\Columns\TextColumn::make('created_at')->label('创建时间')->sortable()
            ])
            ->filters([
                //
            ])
            ->actions([
                Tables\Actions\Action::make('permissions')->label('权限')
                    ->form([
                        PermissionCheckList::make('permissions')->label('权限')->default(function ($record, PermissionCheckList $component) {
                            return array_intersect($record->permissions->pluck('permission')->toArray(), collect($component->getPermissions())->pluck('permissions')->collapse()->keys()->toArray());
                        })
                    ])->action(function ($data, $record) {
                        $oldPermissions = $record->permissions->pluck('permission')->toArray();
                        dump($oldPermissions);
                        $needDeletes = array_diff($oldPermissions, $data['permissions']);
                        dump($needDeletes);
                        $needCreates = array_diff($data['permissions'], $oldPermissions);
                        DB::transaction(function () use ($record, $needCreates, $needDeletes) {
                            $record->permissions()->whereIn('permission', $needDeletes)->delete();
                            $record->permissions()->insert(array_map(function ($permission) use ($record) {
                                return [
                                    'permission' => $permission,
                                    'role_id' => $record->id,
                                    'created_at' => Carbon::now(),
                                    'updated_at' => Carbon::now(),
                                ];
                            }, $needCreates));
                        });
                        return Notification::make()->title('设置成功')->success()->send();
                    })->visible(fn() => static::checkPermission('permission')),
                Tables\Actions\EditAction::make(),
                Tables\Actions\DeleteAction::make()->using(function (Role $record) {
                    $record->permissions()->delete();
                    $record->delete();
                    return true;
                })
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ])
            ->defaultSort('id', 'DESC');
    }

    public static function getRelations(): array
    {
        return [
            //
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListRoles::route('/'),
        ];
    }
}
